package org.musicguardian.core.jobs;

import java.io.File;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.musicguardian.core.Activator;
import org.musicguardian.core.Core;
import org.musicguardian.core.model.Library;
import org.musicguardian.core.scan.Scanner;
import org.musicguardian.core.scan.local.DirectoryScanner;
import org.musicguardian.core.transactions.LocalLibraryCreateTransaction;

public class JobDirectoryScanner extends Job {

	private final File directory;

	public JobDirectoryScanner(File directory) {
		super("Scanning directory " + directory.getPath());
		this.directory = directory;
	}

	@Override
	protected IStatus run(final IProgressMonitor monitor) {
	    DirectoryScanner scanner;
		try {
			scanner = new DirectoryScanner(directory);
			monitor.beginTask("", scanner.getTotalWork());
			scanner.addScannerListener(new DirectoryScanner.ScannerListener() {
				public void fileScanned(Object scannedObject) {
					monitor.worked(1);
					monitor.setTaskName("Scanning file : " + scannedObject.toString());
				}

			});
			Library newLibrary = scanner.run();
			Core.getInstance().runTransaction(new LocalLibraryCreateTransaction(newLibrary));
		} catch (Exception e) {
			return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
					IStatus.ERROR, "Scanner error", e);
		} finally {
			monitor.done();
		}
		return Status.OK_STATUS;
	}

}
